import React, {useState, useEffect, useContext} from 'react';
import XLSX from 'xlsx';
import saveAs from 'file-saver';

import {LedgerContext} from '../../Ledger';

export default ({hidden, tableName, displayName, proc=e=>e}) => {

  const [status, setStatus] = useState('DONE');

  const {books} = useContext(LedgerContext);

  useEffect(() => {
    if(status === 'EXPORT'){
      (async() => {
        try {
          const sheets = proc(tableName, books);
          const workbook = XLSX.utils.book_new();

          for (let [sheetName, data] of Object.entries(sheets)) {
            const worksheet = XLSX.utils.json_to_sheet(data);
            XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
          }

          const buffer = XLSX.write(workbook, { bookType:'xlsx', bookSST:false, type:'array'});
          saveAs(new Blob([buffer],{type:"application/octet-stream"}), `导出-${tableName}.xlsx`);
          setStatus('DONE');
        } catch (err) {
          console.error(err);
          setStatus('DEAD');
        }
      })();
    }
  }, [status])

  const getExport = () => {
    setStatus('EXPORT');
  }

  const elem = hidden
  ? <div key="export"></div>
  : <button key="export" className="button" onClick={() => getExport()}>{displayName}</button>

  return [elem]
}
